#include "mbdexportio.h"
#include "mbdexportedit.h"
#include "MBDExportUtil.h"

MBDExportIO::MBDExportIO(QObject *parent)
    : DataIOInterface()
{
    qDebug() << "MBDEXPORT";
}

QString MBDExportIO::name() const
{
    return tr("MBDExport");
}
void MBDExportIO::initialize()
{
    // 初始化数据库连接
}
QString MBDExportIO::parentMenuName()
{
    return tr("MBD Export");
}
QStringList MBDExportIO::supportedExportFormats() const
{
    return {"MBDLam"};
}
IoEditFrameInterface *MBDExportIO::exportUI(const QString &strFormat) const
{
    if (strFormat == "MBDLam") {
        return new MBDExportEdit();
    }
    return nullptr;
}
QStringList MBDExportIO::supportedImportFormats() const
{
    return {""};
}

QVariantMap MBDExportIO::infoModels() const
{
    return {
        {"ProjectionInfo", tr("Projection Configuration")},
        {"OutputSettings", tr("Output Parameters")}
    };
}

QStringList MBDExportIO::exportInfoHeaders(const QString &format) const
{
    if (format == "MBDLam") {
        QStringList header;
        header << "Document"
               << "Name"
               << "Laminates"
               << "Start Component"
               << "End Component"
               << "Output Directory"
               << "File Name";
        return header;
    }

    return {};
}

QVector<QVariantMap> MBDExportIO::exportInfoModels(const QString &format) const
{
    // TODO: 实现从数据库获取导出数据
    if (format == "MBDLam") {
        Sqltool::instance().changeInfoDb();
        const auto sqlModels = Sqltool::instance().selectAllByTableName(FIBMBDTABLENAME);

        QMap<QString, QString> keys{{"Document", "id"},
                                    {"Name", "Name"},
                                    {"Laminates", "Laminates"},
                                    {"Start Component", "LastOkRunTime"},
                                    {"End Component", "LastOkRunUser"},
                                    {"Output Directory", "DesignBoundary"},
                                    {"File Name", "TreeWriter"}};
        QVector<QVariantMap> rets;
        for (const auto& model : sqlModels) {
            QVariantMap info;
            for (auto it = keys.begin(); it != keys.end(); ++it) {
                info[it.key()] = model[it.value()];
            }
            rets.push_back(info);
        }
        return rets;
    }
    return {};
}

void MBDExportIO::removeTable(const QString &format, const QStringList &removeNames)
{
    if (format == "MBDLam") {
        Sqltool::instance().changeInfoDb();
        QMultiMap<QString, QVariant> conditionMap;
        for (const auto& name : removeNames)
            conditionMap.insert("Name", name);
        Sqltool::instance().deleteItemsByConditions(ANALYSISPLYTABLENAME, conditionMap);
    }
}

IoEditFrameInterface *MBDExportIO::importUI(const QString &strFormat) const
{
    return nullptr;
}
